<template>
  <div class="box">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="80px"
            class="flex-bettom"
          >
            <div class="flex">
              <el-form-item
                v-if="userType == '00'"
                label="所属网点"
                prop="networkLevel"
              >
                <el-select
                  v-model="form.networkLevel"
                  placeholder="请选择所属网点"
                  style="width: 275px"
                  @change="bg"
                >
                  <el-option
                    v-for="item in networkList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="时间" prop="time">
                <el-date-picker
                  v-model="form.time"
                  style="width: 650px"
                  type="daterange"
                  range-separator="至"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="mxDateChange"
                />
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="mxClear">重置</el-button>
              <el-button icon="el-icon-upload2" plain @click="exportData"
                >导出</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openSetting"
                >承包区参数配置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div v-if="!isObjectEmpty(tableData)">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData.list.data"
            tooltip-effect="dark"
            style="width: 100%"
            border
            row-key="id"
            :tree-props="{ children: 'children' }"
            max-height="700"
          >
            <el-table-column
              v-for="(t, n) in tableData.fields"
              :key="n"
              :prop="t.fields"
              :label="t.translate"
              :fixed="n < 2"
              :min-width="
                flexColumnWidth(t.translate, t.fields, tableData.list.data)
              "
              align="center"
            >
              <template slot-scope="{ row, $index }">
                <a
                  v-if="t.isPoint != null"
                  style="color: skyblue"
                  @click="searchDetail(row, t)"
                  >{{ row[t.fields] }}</a
                >
                <el-input
                  v-else-if="t.isEdit && row.children"
                  type="text"
                  v-model="row[t.fields]"
                  style="width: 60px; border: none; text-align: center"
                  @blur="saveEdit(row, $index, t.fields)"
                />
                <span v-else>{{ row[t.fields] }}</span>
              </template>
              <el-table-column
                v-for="(s, i) in t.sunList"
                v-show="s.sunList != null"
                :key="i"
                :prop="s.fields"
                :label="s.translate"
                :min-width="
                  flexColumnWidth(s.translate, s.fields, tableData.list.data)
                "
                align="center"
              >
                <template slot-scope="{ row, $index }">
                  <a
                    v-if="s.isPoint != null"
                    style="color: skyblue"
                    @click="searchDetail(row, s)"
                    >{{ row[s.fields] }}</a
                  >
                  <el-input
                    v-else-if="s.isEdit && row.children"
                    type="text"
                    v-model="row[s.fields]"
                    style="width: 60px; border: none; text-align: center"
                    @blur="saveEdit(row, $index, s.fields)"
                  />
                  <span v-else>{{ row[s.fields] }}</span>
                </template>
                <el-table-column
                  v-for="(a, b) in s.sunList"
                  v-show="a.sunList != null"
                  :key="b"
                  :prop="a.fields"
                  :label="a.translate"
                  :min-width="
                    flexColumnWidth(a.translate, a.fields, tableData.list.data)
                  "
                  align="center"
                >
                  <template slot-scope="{ row, $index }">
                    <a
                      v-if="a.isPoint != null"
                      style="color: skyblue"
                      @click="searchDetail(row, a)"
                    >
                      {{ row[a.fields] }}
                    </a>
                    <el-input
                      v-else-if="a.isEdit && row.children"
                      type="text"
                      v-model="row[a.fields]"
                      style="width: 60px; border: none; text-align: center"
                      @blur="saveEdit(row, $index, a.fields)"
                    />
                    <span v-else>{{ row[a.fields] }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="isObjectEmpty(tableData)">
          <empty />
        </div>
      </el-col>
    </el-row>
    <div class="block" style="display: flex; justify-content: flex-end">
      <el-pagination
        :current-page="form.pageDate.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="form.pageDate.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 承包区配置参数弹框 -->
    <el-dialog
      title="承包区配置参数"
      :visible.sync="dialogFormVisible1"
      width="30%"
    >
      <el-form ref="updateParams" :model="updateParams" :rules="rules1">
        <el-form-item
          label="查询配置参数"
          :label-width="formLabelWidth"
          prop="id"
        >
          <el-row>
            <el-col>
              <div style="width: 50%">
                <el-select
                  v-model="updateParams.id"
                  placeholder="请选择"
                  @change="handleSelect"
                >
                  <el-option
                    v-for="item in networkNamelist"
                    :key="item.id"
                    :label="item.networkName"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="航海单票扣款" :label-width="formLabelWidth">
          <el-input
            v-model="updateParams.voyageTicketDeduction"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="政策互惠单票扣款" :label-width="formLabelWidth">
          <el-input
            v-model="updateParams.policyReciprocityTicketDeduction"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="星计划单票扣款" :label-width="formLabelWidth">
          <el-input
            v-model="updateParams.starPlanTicketDeduction"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="网点派费调整" :label-width="formLabelWidth">
          <el-input v-model="updateParams.paiFeeAdjust" style="width: 50%" />
        </el-form-item>
        <el-form-item label="是否参与统计" :label-width="formLabelWidth">
          <el-radio-group v-model="updateParams.isCalculate">
            <el-radio :label="'0'">是</el-radio>
            <el-radio :label="'1'">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="uodateParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {
//   getOutletsList,
//   getSubjectFirstList,
//   getSubjectList,
//   subjectSearch,
//   addSubject,
// } from "@/api/dashboard";
import { editDeliveryMarginData } from "@/api/statisticalCenter";
import {
  InboundGrossProfitinit,
  Getcblist,
  Getupdatecs,
  Getupdateidlist,
} from "@/api/apifile/Networkfinance";
import empty from "@/components/menuComponent/empty.vue";
import { exportDataCGPJML } from "@/api/home";

export default {
  components: { empty },
  data() {
    return {
      userType: localStorage.getItem("userType") || null,
      isart: false,
      networkNamelist: [],
      form: {
        networkLevel: 0,
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      updateData: {},
      loading: false,
      formLabelWidth: "130px",
      addForm: {
        networkNameId: "",
        firstId: "",
        secondName: "",
      },
      // 一级网点
      SubjectFirstList: [],
      // 网点列表
      networkList: [
        { value: 0, label: "网点" },
        { value: 1, label: "承包区" },
      ],
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogFormVisible1: false,
      currentPage4: 4,
      tableData: {
        list: {
          data: [],
        },
      },
      oldTableData: {},
      rules: {
        networkLevel: [
          { required: true, message: "请选择网点名称", trigger: "blur" },
        ],
        time: [{ required: true, message: "请选择日期", trigger: "blur" }],
      },
      searchForm: {
        contractArea: "",
        settleNetworkNameId: "",
        type: "",
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      dialogFormVisible: false,
      updateParams: {
        id: "",
        networkName: "",
        paiFeeAdjust: null,
        policyReciprocityTicketDeduction: null,
        starPlanTicketDeduction: null,
        voyageTicketDeduction: null,
        isCalculate: "0",
      },
      rules1: {
        id: [{ required: true, message: "请选择配置参数", trigger: "change" }],
      },
    };
  },
  async created() {
    // this.getList();
    // this.getOutLet();
    // this.getSubjectFirst();
    const res = await Getcblist();
    // // console.log(res)
    this.networkNamelist = res.data;
  },
  methods: {
    saveEdit(row, index, name) {
      if (row[name] != this.oldTableData.list.data[index][name]) {
        editDeliveryMarginData(row).then((res) => {
          if (res.code === 200) {
            this.$message("修改成功，正在更新数据");
            this.search();
          }
        });
      }
    },
    // 打开配置弹窗
    openSetting() {
      this.dialogFormVisible1 = true;
    },
    // 根据id获取数据
    handleSelect(val) {
      // // console.log('选择', val)
      this.updateParams.id = val;
      this.getSelectContractAreaSend(val);
    },
    // 获取承包区配置
    getSelectContractAreaSend(contractAreaId) {
      // console.log("contractAreaId:", contractAreaId);
      Getupdateidlist(contractAreaId).then((res) => {
        if (res.code === 200) {
          if (res.data === null) {
            this.updateParams = {};
            return;
          }
          this.updateParams = res.data;
          // // console.log('res', res)
        }
      });
    },
    // 修改承包区配置
    uodateParams() {
      this.$refs.updateParams.validate((valid) => {
        if (valid) {
          Getupdatecs(this.updateParams).then((res) => {
            if (res.code === 200) {
              this.dialogFormVisible1 = false;
              this.$message("修改成功，正在更新数据");
              // this.init()
            }
          });
        } else {
          return false;
        }
      });
    },
    exportData() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.$notify.info({
            title: "开始准备下载...",
          });
          exportDataCGPJML(this.form).then((res) => {
            const url = window.URL.createObjectURL(new Blob([res]), {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "进港派件毛利报表.xlsx"); // 设置下载的文件名
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
            this.$notify({
              title: "下载成功",
              type: "success",
            });
          });
        }
      });
    },
    searchDetail(item, type) {
      // // console.log(item)
      this.searchForm.contractArea = this.networkList.filter(
        (el) => el.value === this.form.networkLevel
      )[0].label;
      this.searchForm.settleNetworkNameId = item.name;
      this.searchForm.type = type.isPoint;
      this.$store.state.app.jgpjmltab = this.searchForm;
      this.$router.push({
        path: "InboundGrossProfitDetail",
      });
    },
    isObjectEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    bg(value) {
      // // console.log(value)
      if (value === 2) {
        this.isart = true;
      } else {
        this.isart = false;
      }
    },
    handleSizeChange(val) {
      this.form.pageDate.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.form.pageDate.pageNum = val;
      this.init();
    },
    mxClear() {
      this.$refs.form.resetFields();
      this.form.startTime = "";
      this.form.endTime = "";
    },

    search() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.init();
        }
      });
    },
    init() {
      this.loading = true;
      InboundGrossProfitinit(this.form).then((res) => {
        // console.log("查询", res);
        if (res.code === 200) {
          this.tableData = res.data;
          this.oldTableData = JSON.parse(JSON.stringify(this.tableData));
          this.total = res.data.list.total;
          this.form.pageDate.pageNum = res.data.list.current;
          // console.log(this.tableData);
          this.$message.success("查询成功");
          this.pages.pageNum = res.data.current;
        }
        this.loading = false;
      });
    },
    mxDateChange(value) {
      if (value != null) {
        this.searchForm.startTime = value[0];
        this.searchForm.endTime = value[1];
        this.form.startTime = value[0];
        this.form.endTime = value[1];
      }
    },
    // 获取网点列表
    // getOutLet() {
    //   getOutletsList().then((res) => {
    //     if (res.code === 200) {
    //       this.networkList = res.data
    //     }
    //   })
    // },
    // 获取一级网点下拉框
    // getSubjectFirst() {
    //   getSubjectFirstList().then((res) => {
    //     if (res.code === 200) {
    //       this.SubjectFirstList = res.data
    //     }
    //   })
    // },
    // 显示表格数据
    getList() {
      // getSubjectList().then((res) => {
      //   if (res.code === 200) {
      //     this.tableData = res.data.data
      //     this.total = res.data.total
      //     this.pages = res.data.pages
      //   } else {
      //     this.$message({
      //       message: res.msg,
      //       type: 'warning'
      //     })
      //   }
      // })
    },

    // 重置

    handleSelectionChange(val) {
      // this.multipleSelection = val;
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-bettom {
  display: flex;
  justify-content: space-between;
}

.header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
